import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { CommonService } from '../../../../services-common/common.service';
import { SecondCouponService } from '../services/second-coupon.service';

@Component({
  selector: 'app-second-coupon-edit',
  templateUrl: './second-coupon-edit.component.html',
  styleUrls: ['./second-coupon-edit.component.scss'],
  providers: [DatePipe]
})
export class SecondCouponEditComponent implements OnInit {

  routeParams: any = {};
  detailForms: any = {};
  formParams: any = {
    status: 5, // 状态 默认 5草稿
    type: 1, // 活动类型：1、满减型 2、折扣型 3、随机券
    name: '', // 优惠券名称
    remark: '', // 备注
    total: '', // 发放总量
    orderLimitMoney: '', // 使用门槛
    orderLimitMoneyCheck: false, // 门槛知晓风险
    limitSmall: '', // 减免额度 or 折扣力度 or 优惠金额最小值
    limitBig: '', // 最高减免金额 or 优惠金额最大值 (没有传0)

    isShowWeb: 1, // 默认展示 0：不展示 1：展示
    getBeginTime: '', // 可领取开始时间
    getEndTime: '', // 可领取结束时间
    userType: 0, // 领取人限制 0：不限制 1：C端用户 2：B端用户

    limitTimeNum: 0, // 限制使用 xx天 0：当天 1：明天
    useBeginTime: '', // 限制使用开始时间
    useEndTime: '', // 限制使用结束时间
    useDesc: '', // 使用说明

    // containsTypes: '', // 品牌list 0：为全部 -1：为全不选
    // containsSeries: '', // 系列list 0：为全部 -1：为全不选
    containsModel: '', // 机型list 0：为全部 -1：为全不选
    containsSupplier: '', // 货主list 0：为全部 -1：为全不选
    containsColourB: '', // B端成色list 0：为全部 -1：为全不选
    containsColourC: '', // C端成色list 0：为全部 -1：为全不选
    filterGoods: '', // 排除商品list 0：为全部
    containsGoods: '', // 追加商品list 0：为全部
    
    remind: '0', // 过期N天提醒(参考优惠券、暂无用、用作提交)
    userLimitNum: '1', // 没人限领次数(参考优惠券、暂无用、用作提交)
    autoReverse: '0' // 每N天首次进店自动发放(参考优惠券、暂无用、用作提交)
  };
  availableDates: any[] = []; // 可领取时间Array
  limitDates: any[] = []; // 限制使用时间Array
  limitUseGroup: number = 1; // 限制使用时间Radios 1：天 2：时间段

  supplierOptions: any = []; // 供应商 | 货主
  supplierSelected: any = []; // 供应商 | 货主

  modelAll: boolean = false; // 机型全选
  supplierAll: boolean = false; // 货主全选

  // 成色B端 options
  conditionOptionsB: any = [];
  selectConditionB: any = [];

  // 成色C端 options
  conditionOptionsC: any = [];
  selectConditionC: any = [];

  // 选择指定机型
  isModelVisible = false;
  defaultModelKeys: any[] = [];

  // 指定商品勾选 Modal
  modalGoodsType: number = 1; // 1：排除可用 2：追加可用
  isGoodsVisible = false;
  modelGoodOptions: any = [];
  disabledOptions: any = [];

  excludeGoodsIds: any = []; // 排除可用ids
  addGoodsIds: any = []; // 追加可用ids

  // 查看已选商品 Modal
  isPreviewVisible = false;
  previewGoodIds: any = [];
  previewTable: any = [];

  // 审核 Modal
  isExamineVisible = false;
  examineParams = {
    remark: ''
  };

  constructor(
    private message: NzMessageService,
    private datePipe: DatePipe,
    private activatedRoute: ActivatedRoute,
    private commonService: CommonService,
    private services: SecondCouponService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    if (['1', '3'].includes(this.routeParams.type)) {
      this.loadDetails();
    } else {
      this.loadSupplierOptions();
      this.initconditionDatas();
    }
  }

  async loadDetails() {
    await this.loadSupplierOptions();
    await this.initconditionDatas();

    const messId = this.message.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const { code, data, message }: any = await this.services.getCouponUpdateDetail(this.routeParams.id);
    this.message.remove(messId);

    if (code === 0) {
      this.detailForms = data;

      this.formParams.status = data.status; // 状态
      if (this.routeParams.type === '3') {
        this.detailForms.status = 5;
        this.formParams.status = 5;
      }

      this.formParams.type = data.type; // 类型
      this.formParams.name = data.name; // 优惠券名称
      this.formParams.remark = data.remark || ''; // 备注
      this.formParams.total = data.total; // 发放总量
      this.formParams.orderLimitMoney = data.orderLimitMoney; // 使用门槛
      this.formParams.orderLimitMoneyCheck = data.orderLimitMoney === 0 ? true : false; // 勾选知晓
      this.formParams.limitSmall = data.limitSmall; // 减免额度 or 折扣力度 or 优惠金额最小值
      this.formParams.limitBig = data.limitBig; // 最高减免金额 or 优惠金额最大值

      this.formParams.isShowWeb = data.isShowWeb; // 默认展示
      this.formParams.getBeginTime = data.getBeginTime || ''; // 可领取开始时间
      this.formParams.getEndTime = data.getEndTime || ''; // 可领取结束时间
      this.availableDates = data.isShowWeb == 1 ? [data.getBeginTime, data.getEndTime] : []; // 可领取时间Array
      this.formParams.userType = data.userType; // 领取人限制

      // 限制使用时间
      if (data.limitTimeNum == '-1') {
        this.limitUseGroup = 2;
        this.formParams.useBeginTime = data.useBeginTime;
        this.formParams.useEndTime = data.useEndTime;
        this.limitDates = [data.useBeginTime, data.useEndTime];
      } else {
        this.limitUseGroup = 1;
        this.formParams.limitTimeNum = data.limitTimeNum;
      }
      // 使用说明
      this.formParams.useDesc = data.useDesc;

      // 指定机型
      switch (data.containsModel) {
        case '0':
          this.modelAll = true;
          break;
        case '-1':
          this.modelAll = false;
          break;
        default:
          this.modelAll = false;
          break;
      }
      // this.formParams.containsTypes = data.containsTypes;
      // this.formParams.containsSeries = data.containsSeries;
      this.formParams.containsModel = data.containsModel;
      // let brandArr = ['0', '-1'].includes(data.containsTypes) ? [] : data.containsTypes.split(',');
      // let seriesArr = ['0', '-1'].includes(data.containsSeries) ? [] : data.containsSeries.split(',');
      let modelArr = this.commonService.isEmpty(data.containsModel) || ['0', '-1'].includes(data.containsModel) ? [] : data.containsModel.split(',');
      this.defaultModelKeys = [...modelArr];

      // 货主
      if (data.containsSupplier === '-1') {
        this.supplierAll = false;
        this.supplierSelected = [];
      } else {
        let tempSuppList = data.containsSupplier.split(',').map((m: any) => +m);
        if (tempSuppList.length === this.supplierOptions.length) {
          this.supplierAll = true;
        } else {
          this.supplierAll = false;
        }
        this.supplierSelected = tempSuppList;
      }
      
      // B端成色
      if (data.containsColourB === '0') {
        this.selectConditionB = this.conditionOptionsB.map((item: any) => item.id);
      } else if (data.containsColourB === '-1') {
        this.selectConditionB = [];
      } else {
        this.selectConditionB = data.containsColourB.split(',').map((m: any) => +m);
      }

      // C端成色
      if (data.containsColourC === '0') {
        this.selectConditionC = this.conditionOptionsC.map((item: any) => item.id);
      } else if (data.containsColourB === '-1') {
        this.selectConditionC = [];
      } else {
        this.selectConditionC = data.containsColourC.split(',').map((m: any) => +m);
      }
      
      this.formParams.filterGoods = data.filterGoods; // 排除商品
      this.excludeGoodsIds = (data.filterGoods && data.filterGoods != '0') ? data.filterGoods.split(',') : []; // 排除商品Ids
      this.formParams.containsGoods = data.containsGoods; // 追加商品
      this.addGoodsIds = (data.containsGoods && data.containsGoods != '0') ? data.containsGoods.split(',') : []; // 追加商品商品Ids
    } else {
      this.message.error(message);
    }
  }

  // 查询供应商 | 货主
  async loadSupplierOptions() {
    const { code, message, data }: any = await this.services.querySupplierList();
    if (code === 0) {
      this.supplierOptions = data.records.length ? data.records.filter((item: any) => item.name) : [];
      this.supplierOptions.unshift({
        id: 0,
        name: '自营'
      })
    } else {
      this.message.error(message);
    }
  }

  // 成色options
  async initconditionDatas() {
    this.conditionOptionsB = await this.commonService.getDictList('machine_condition_b');
    this.conditionOptionsC = await this.commonService.getDictList('machine_condition');
  }

  /**
   * ----------------------------------------------------------------
   * 指定机型 Modal Select Tree
   * ----------------------------------------------------------------
   */
  selectMoreModel() {
    this.defaultModelKeys = [];
    this.defaultModelKeys = this.mergeTreeKey();
    this.isModelVisible = true;
  }

  subModelTree(objs: any) {
    // this.formParams.containsTypes = objs.brandList.join(',');
    // this.formParams.containsSeries = objs.seriesList.join(',');
    this.formParams.containsModel = objs.modelList.join(',');
    this.defaultModelKeys = this.mergeTreeKey();
    if (this.defaultModelKeys.length) {
      this.modelAll = false;
    }
  }

  mergeTreeKey() {
    // let brandArr = this.formParams.containsTypes ? this.formParams.containsTypes.split(',') : [];
    // let seriesArr = this.formParams.containsSeries ? this.formParams.containsSeries.split(',') : [];
    let modelArr = (this.commonService.isEmpty(this.formParams.containsModel) || this.formParams.containsModel == '0' || this.formParams.containsModel == '-1') ? [] : this.formParams.containsModel.split(',');
    return modelArr.length ? [...modelArr].map((item: any) => +item) : [];
  }

  /**
   * ----------------------------------------------------------------
   * 商品选择 Modal Table
   * ----------------------------------------------------------------
   */
  showSelectGoods(type: number) {
    // type 1：排除可用 2：追加可用
    if (type === 1) {
      this.modelGoodOptions = this.excludeGoodsIds;
      this.disabledOptions = this.addGoodsIds;
    } else {
      this.modelGoodOptions = this.addGoodsIds;
      this.disabledOptions = this.excludeGoodsIds;
    }
    this.modalGoodsType = type;
    this.isGoodsVisible = true;
  }

  submitSelectGoods(obj: any) {
    // 1：排除可用 2：追加可用
    if (this.modalGoodsType === 1) {
      this.excludeGoodsIds = obj.ids;
    } else {
      this.addGoodsIds = obj.ids;
    }
  }

  /**
   * ----------------------------------------------------------------
   * 勾选预览 Modal Table
   * ----------------------------------------------------------------
   */
  previewModal(type: number) {
    if (type === 1) {
      this.previewGoodIds = this.excludeGoodsIds;
    } else {
      this.previewGoodIds = this.addGoodsIds;
    }
    this.isPreviewVisible = true;
  }

  addExcludeChange(result: Array<any>) {
    this.modelGoodOptions = [...result];
  }

  // params handle 0：为全部 -1：为全不选
  paramHandle(state: boolean, result: any) {
    let tempStr = '';
    if (state) {
      tempStr = '0';
    } else if (!state && !result.length) {
      tempStr = '-1';
    } else {
      if (Object.prototype.toString.call(result) === '[object Array]') {
        tempStr = result.join(',');
      } else {
        tempStr = result;
      }
    }
    return tempStr;
  }

  /**
   * submit 提交审核 | 保存
   * @param status 5：草稿 6：待审核
   * @returns 
   */
  async submitForms(status: number) {
    if (!this.isVerifForms()) {
      return
    }
    let params = {
      ...this.formParams,
      limitBig: this.isEmpty(this.formParams.limitBig) ? '0' : this.formParams.limitBig,
      limitTimeNum: this.limitUseGroup === 2 ? '-1' : this.formParams.limitTimeNum, // 限制使用时间
      // containsTypes: this.paramHandle(this.modelAll, this.formParams.containsTypes), // 品牌
      // containsSeries: this.paramHandle(this.modelAll, this.formParams.containsSeries), // 系列
      containsModel: this.paramHandle(this.modelAll, this.formParams.containsModel), // 机型
      containsSupplier: (!this.supplierAll && !this.supplierSelected.length) ? '-1' : this.supplierSelected.join(','), // 货主
      isSup: this.supplierAll ? 0 : 1, // 0全选 1不全选(后端判断可用商品使用)
      containsColourB: this.selectConditionB.length === 0 ? -1 : this.selectConditionB.length === this.conditionOptionsB.length ? 0 : this.selectConditionB.join(','),
      containsColourC: this.selectConditionC.length === 0 ? -1 : this.selectConditionC.length === this.conditionOptionsC.length ? 0 : this.selectConditionC.join(','),
      filterGoods: this.excludeGoodsIds.length ? this.excludeGoodsIds.join(',') : '0', // 排除商品
      containsGoods: this.addGoodsIds.length ? this.addGoodsIds.join(',') : '0' // 追加商品
    }
    if (status === 6) {
      params.status = 6;
    }
    // return
    let res: any;
    if (['0', '3'].includes(this.routeParams.type)) {
      res = await this.services.addCouponData(params);
    } else {
      res = await this.services.editCouponData(params, this.routeParams.id);
    }
    if (res.code === 0) {
      this.message.success('操作成功');
      this.back();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 审核
   * ----------------------------------------------------------------
   */
  showExamineModal() {
    this.examineParams.remark = '';
    this.isExamineVisible = true;
  }

  // Type 1：通过 7：不通过
  async subExamine(type: number) {
    if (type === 7 && !this.examineParams.remark) {
      this.message.warning('请输入审核意见');
      return
    }
    let params = {
      id: this.routeParams.id,
      reviewRemark: this.examineParams.remark,
      status: type
    }
    const { code, message }: any = await this.services.examineCouponItem(params);

    if (code === 0) {
      this.isExamineVisible = false;
      this.message.success('操作成功');
      this.back();
    } else {
      this.message.error(message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 验证
   * ----------------------------------------------------------------
   */
  isVerifForms() {
    if (this.isEmpty(this.formParams.name)) {
      this.message.warning('请输入优惠券名称');
      return false;
    } else if (this.isEmpty(this.formParams.total)) {
      this.message.warning('请输入发放总量');
      return false;
    } else if (this.isEmpty(this.formParams.orderLimitMoney)) {
      this.message.warning('请输入使用门槛');
      return false;
    } else if (this.formParams.orderLimitMoney == 0 && !this.formParams.orderLimitMoneyCheck) {
      this.message.warning('无门槛优惠券可能带来风险,请勾选确认');
      return false;
    } else if (this.formParams.type === 1 && this.isEmpty(this.formParams.limitSmall)) {
      // ------ 满减 1 ------
      this.message.warning('请输入减免额度');
      return false;
    } else if (this.formParams.type === 2 && this.isEmpty(this.formParams.limitSmall)) {
      // ------ 满折 2 ------
      this.message.warning('请输入折扣力度');
      return false;
    } else if (this.formParams.type === 2 && this.isEmpty(this.formParams.limitBig)) {
      // ------ 满折 2 ------
      this.message.warning('请输入最高减免金额');
      return false;
    } else if (this.formParams.type === 3 && (this.isEmpty(this.formParams.limitSmall) || this.isEmpty(this.formParams.limitBig))) {
      // ------ 随机 3 ------
      this.message.warning('请输入优惠金额');
      return false;
    } else if (!this.availableDates.length && this.formParams.isShowWeb === 1) {
      this.message.warning('请输入可领取时间');
      return false;
    } else if ((this.limitUseGroup === 1 && this.isEmpty(this.formParams.limitTimeNum)) || (this.limitUseGroup === 2 && !this.limitDates.length)) {
      this.message.warning('请输入限制使用时间');
      return false;
    } else if (this.isEmpty(this.formParams.useDesc)) {
      this.message.warning('请输入使用说明');
      return false;
    } else {
      return true;
    }
  }

  // 门槛验证
  thresholdVerif() {
    if (this.formParams.orderLimitMoney && this.formParams.orderLimitMoney > 0) {
      switch (this.formParams.type) {
        case 1:
          // console.log('满减券');
          if (Number(this.formParams.limitSmall) && Number(this.formParams.limitSmall) > Number(this.formParams.orderLimitMoney)) {
            this.message.warning('使用门槛值需大于或等于减免额度值!');
            this.formParams.orderLimitMoney = '';
          }
          break;
        case 3:
          // console.log('随机券');
          if (this.formParams.limitSmall && this.formParams.limitBig) {
            let tempMax = Math.max.apply(Math, [this.formParams.limitSmall, this.formParams.limitBig]);
            if (tempMax > this.formParams.orderLimitMoney) {
              this.message.warning('使用门槛值需大于或等于优惠金额最大值!');
              this.formParams.orderLimitMoney = '';
            }
          }
          break;
      }
    }
  }

  // 减免金额验证(num：0--减免额度,1：最高减免金额)
  reductionVerif(num: number) {
    if (this.formParams.orderLimitMoney && this.formParams.orderLimitMoney > 0) {
      if (num == 0) {
        if (this.formParams.limitSmall && Number(this.formParams.limitSmall) > Number(this.formParams.orderLimitMoney)) {
          this.message.warning('减免额度值需小于或等于使用门槛值!');
          this.formParams.limitSmall = '';
        }
      } else {
        if (this.formParams.limitBig && Number(this.formParams.limitBig) > Number(this.formParams.orderLimitMoney)) {
          this.message.warning('最高减免金额值需小于或等于使用门槛值!');
          this.formParams.limitBig = '';
        }
      }

    }
  }

  // 优惠金额输入验证
  rangeValueVerif() {
    if (this.formParams.limitSmall && this.formParams.limitBig) {
      if (this.formParams.limitSmall > this.formParams.limitBig) {
        this.message.warning('范围内随机值前者不可大于后者!');
        this.formParams.limitSmall = '';
      }

      if (this.formParams.orderLimitMoney && this.formParams.orderLimitMoney > 0) {
        let tempMax = Math.max.apply(Math, [this.formParams.limitSmall, this.formParams.limitBig]);
        if (tempMax > this.formParams.orderLimitMoney) {
          this.message.warning('优惠金额最大值需小于或等于使用门槛值!');
          this.formParams.limitSmall = '';
          this.formParams.limitBig = '';
        }
      }
    }
  }

  /**
   * ----------------------------------------------------------------
   * 组件操作
   * ----------------------------------------------------------------
   */

  // 券类type change
  couponTypeChange(event: number) {
    this.formParams.limitSmall = '';
    this.formParams.limitBig = '';
  }

  // 日期选择change
  onDateChange(result: any[], keyArrs: Array<string>) {
    this.formParams[keyArrs[0]] = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd HH:mm') + ':00' : '';
    this.formParams[keyArrs[1]] = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd HH:mm') + ':00' : '';
  }

  // 限制时间change
  limitGroupChange(val: any) {
    this.formParams.limitTimeNum = 0;
    this.formParams.useBeginTime = '';
    this.formParams.useEndTime = '';
    this.limitDates = [];
  }

  /**
   * 机型 | 货主全选 Change
   * @param val 
   * @param type 1：机型 2：货主
   */
  modelOwnerAllChange(val: any, type: number) {
    switch (type) {
      case 1:
        this.formParams.containsModel = '';
        this.defaultModelKeys = [];
        break;
      case 2:
        this.supplierSelected = this.supplierOptions.map((item: any) => item.id);
        break;
    }
  }

  /**
   * 机型 | 货主 ** 全不选 **
   * @param type 1：机型 2：货主
   */
  modelOwnerNotAllChange(type: number) {
    switch (type) {
      case 1:
        this.modelAll = false;
        this.formParams.containsModel = '';
        this.defaultModelKeys = [];
        break;
      case 2:
        this.supplierAll = false;
        this.supplierSelected = [];
        break;
    }
  }

  // 货主 select change
  supplierChange(val: any) {
    if (!val.length || val.length !== this.supplierOptions.length) {
      this.supplierAll = false;
    } else if (val.length === this.supplierOptions.length) {
      this.supplierAll = true;
    }
  }

  // is Empty
  isEmpty(val: any) {
    if (val === '' || val === undefined || val === null) {
      return true;
    } else {
      return false;
    }
  }

  // back
  back() {
    history.back();
  }

  // 前端展示
  isShowChange(val: any) {
    if (val == 0) {
      this.formParams.getBeginTime = '';
      this.formParams.getEndTime = '';
      this.availableDates = [];
    }
  }
}
